//成品新增和编辑页面

var RATE=Number($.cookie("RingRate")) || 1;
var EDITMODE=false;
var xhrVideo = new XMLHttpRequest();
(function(){
	var addForm={
		init:function(){
			myApp.showIndicator();
			this.bindEvents();
			this.loadCommon();
			myApp.hideIndicator();

		},
		bindEvents:function(){
			var self=this;
			$("#rate").text(RATE);
			//编辑
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				ID = args["ID"];//产品ID		
				EDITMODE=true;
			}
			if(EDITMODE){
				$(".category").hide();
				self.bindData(ID);
                getPutPrimeGoldsPrice(); //获取金价
				$("#page_title").html(_("空托编辑"));
			}else{
				$('.category').show();
                getPutPrimeGoldsPrice(); //获取金价
				$("#page_title").html(_("空托新增"));
			}
			//修改新增：采购人
            var html_purchaseAgent = "";
            if (list.msgcode ==true) {
                for(var k in list.msginfo){
                    html_purchaseAgent +='<option value="'+k+'">'+ _(list.msginfo[k]) +'</option>';
                }
            }
            else {
                html_purchaseAgent += "<option></option>";
            }
            $("#purchaseAgent").append(html_purchaseAgent);
			//切换主石类型
			//self.changType(1);
			//self.sizeParams(1);
			$("#data_category").on("click","span",function(){
				$(this).addClass("active").siblings().removeClass("active");
				var type=$("#data_category span.active").attr("data-value");				
				self.changType(type);
			});
			//关闭弹框
			$("#close_tip_btn").on("click",function(){
				$("#tip_box").hide();
			});
			//美金与人民币的转换
			$("#usd_input").bind('input propertychange', function() {
				var usdVal=$(this).val();
				$("#rmb_input").val(formatRMBPrice(usdVal*RATE));
			});
			$("#rmb_input").bind('input propertychange', function() {
				var rmbVal=$(this).val();
				$("#usd_input").val(formatUSDPrice(rmbVal/RATE));
			});

			//采购价格美金和人民币的转换
			$("#purchaseUSDPerGrain").bind('input propertychange', function() {
				var usdVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
				$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
			})

            $("#purchaseRMB").bind('input propertychange', function() {
                var rmbVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
                $("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
            })
            //通过采购汇率计算
            $("#purchaseExchange").bind('input propertychange',function(){
                var purchaseRate=$(this).val();
                var usdVal=$("#purchaseUSDPerGrain").val();
                if(usdVal && purchaseRate){
                	$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
				}
				var rmbVal=$("#purchaseRMB").val();
                if(rmbVal && purchaseRate){
                	$("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
				}

            })

            //计算总价 现货
            $('#SidePrice').on('input', calc6); //副石总额
            $('#NetGoldWeight').on('input', calc6); //总重
            $("#unitPrice").on("input",calc6);// 工费
            $("#wastage").on("input",calc6); // 耗损
            $("#insurance").on("input",calc6);// 保险费
            $("#sideLaborFee").on("input",calc6);// 副石工费
            $("#sideNum").on("input",calc6);// 副石粒数

            //通过材质设置获取金价 现货
            $("#form_material").on("change",function(){
                var sel_this = $(this).val();
                console.log(sel_this)
                $.each(goldJson, function(key,val) {
                    if(sel_this==key){
                        $("#g_price").val(val);
                        var g_val = val;
						var netGoldWeight=$("#NetGoldWeight").val(); //总重
						var wastage=$("#wastage").val(); //耗损
						var sidePrice="";
						if($("#SidePrice").val()!=""){
							sidePrice=$("#SidePrice").val(); //副石金额
						}else{
							sidePrice=0;
						}
						var unitPrice=$("#unitPrice").val(); //工费
						var insurance=$("#insurance").val(); //保险费
                        var SideLaborFee=$("#sideLaborFee").val()*$("#sideNum").val(); //副石工费
						$("#tolPrice").val(formatRMBPrice(parseFloat(g_val)*parseFloat(netGoldWeight)*parseFloat(1+parseFloat(wastage))+parseFloat(sidePrice)+parseFloat(unitPrice)+parseFloat(insurance)+parseFloat(SideLaborFee)));

                    }
                });
            });


			//提交验证
			$("#submit_btn").on("click",function(){
				$("#form_data").submit();
			});
			$("#reset_btn").on("click",function(){
				// if(EDITMODE){
				// 	myApp.alert(_("编辑时不能重置参数！"));
				// }else{
				// 	$("#form_data")[0].reset();
				// }
                $("#form_data")[0].reset();
            });
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                	if($("#SideWeight").val()==""){
                		$("#SideWeight").val(0);
                	}
                	var StyleNo=$("#styleNo").val();
                	self.unImg(StyleNo);
                },
                rules: {
                    OriginSN: "required",
                    StyleNo: "required",
                    Type: "required",
                    Style: "required",
                    Technics: "required",
                    Series: "required",
                    MainShape: "required",
                    MainWeight: "required",
                    TotalWeight: "required",
                    Material: "required",
                    LaborFee: "required" ,
                    NetGoldWeight:"required",
                    Wastage:"required",
                    Insurance:"required",
                    IsStock: "required",
                    Status: "required",
                    Country: "required",
                },
                messages: {
                    OriginSN: "",
                    StyleNo:"",
                    Type: "",
                    Style: "",
                    Series: "",
                    Technics: "",
                    MainShape: "",
                    MainWeight: "",
                    TotalWeight:"",
                    Material: "",
                    LaborFee: "" ,
                    NetGoldWeight:"",
                    Wastage:"",
                    Insurance:"",
                    IsStock: "",
                    Status: "",
                    Country: "",
                }
            });
			
		},
		//编辑时绑定数据
		bindData:function(ID){
			$("#form_reset_btn").attr("disabled", true);
			myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=ID;
			submitJson.GoodsType=7;
			if(EDITMODE){
				submitJson.IsMyStock=true;
			}
			$.ajax({
				url:'/Team/GetProductData',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')')
					if(res.msgcode==true){
						var datas=res.msginfo.rows;	
						var data =datas[0];

                        var options = "";
                        options += '<option data-val="'+data.ReceiptStatus+'" value="'+data.ReceiptStatus+'" selected="selected">'+formatReceiptStatus(data.ReceiptStatus)+'</option>'+
                            '<option data-val="'+ (data.ReceiptStatus==0?1:0) +'" value="'+ (data.ReceiptStatus==0?1:0) +'">'+formatReceiptStatus(data.ReceiptStatus==0?1:0)+'</option>';
                        $("#form_ReceiptStatus").html(options);//--付款

                        $("#form_data").setForm(data);//帮数据
						$("#id_input").prop({"name":"ID","value":data.ID});//ID

                        if(data.ArrivalTime){
                            $("#data_ArrivalTime").val($.trim(YearDateFormats(data.ArrivalTime)));//到货时间
                            // $("#data_ArrivalTime").val($.trim(YearDateFormats(new Date(GetDateDiff(data.ArrivalTime)).getTime())));//到货时间
                        }

                        //推荐
                        $("#form_Tag").val(data.Tag);

                        //总价
                        $("#tolPrice").val(formatRMBPrice((parseFloat(data.GoldPrice)*parseFloat(data.NetGoldWeight)*(1+parseFloat(data.Wastage)))+parseFloat(data.SidePrice)+parseFloat(data.LaborFee)+parseFloat(data.Insurance)+parseFloat(data.SideLaborFee*data.SideNum)));

                        //视频绑定
                        if(data.Videos!=''){
                            var _CRE_FILE = document.createElement("input");
                            _CRE_FILE.setAttribute("type", "file");
                            _CRE_FILE.setAttribute("class", "video_file");
                            _CRE_FILE.setAttribute("id", "video_input");
                            _CRE_FILE.setAttribute("style", "display:none");
                            _CRE_FILE.setAttribute("data-url",data.Videos );
                            $('.video_one').after(_CRE_FILE);
                            var userAgent=navigator.userAgent;
                            if(APP){
                                if(userAgent.indexOf('Android')!=-1 && (data.Videos.indexOf('MOV')!=-1 || data.Videos.indexOf('mov')!=-1) ){
                                    var videoHtml=  '<section class="up-section fl close_f" style="margin-left: 5px; position: relative;">'+
                                        '<span class="up-span"></span>'+
                                        '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()">'+
                                        '<img src="/images/video2.png" style="width: 100%;height: 100%;display: block;">'+
                                        '</section>';
                                }else{
                                    var videoHtml= '<section class="up-section fl close_f"  style="margin-left: 5px; position: relative;width: 136px;height: 136px">'+
                                        '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()" style="display: block">'+
                                        '<embed src="'+data.Videos+'"  style="width: 100%;height: 100%;display: block;">'+
                                        '</section>';
                                }

                            }else{
                                if(data.Videos.indexOf('MOV')!=-1 || data.Videos.indexOf('mov')!=-1){
                                    var videoHtml=  '<section class="up-section fl close_f" style="margin-left: 5px; position: relative;">'+
                                        '<span class="up-span"></span>'+
                                        '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()">'+
                                        '<img src="/images/video2.png" style="width: 100%;height: 100%;display: block;">'+
                                        '</section>';
                                }else{
                                    var videoHtml= '<section class="up-section fl close_f"  style="margin-left: 5px; position: relative;width: 136px;height: 136px">'+
                                        '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()" style="display: block">'+
                                        '<embed src="'+data.Videos+'"  style="width: 100%;height: 100%;display: block;">'+
                                        '</section>';
                                }

                            }
                             $('.video_one').after(videoHtml)


                        }


                        //图片的绑定
						if(data.Images!=""){
							imgs = data.Images.split("|");
							 for (var i=0; i< imgs.length;i++) {
							 	var img_boxHmtl=[
					    			'<section class="up-section fl load">',
										'<span class="up-span"></span>',
										'<img src="/images/a7.png" class="close-upimg"  style="display: block;top:4px;right:2px;width:16px;height:16px" >',
										'<img src=',imgs[i],' class="up-img" data-src=',imgs[i],'>',
										'<p class="img-namep"></p>',
										'<input id="taglocation" name="taglocation" value="" type="hidden">',
										'<input id="tags" name="tags" value="" type="hidden">',
									'</section>'
					    		].join('');
					    		$("#img_box").append(img_boxHmtl);
							 }
						}
					}else{
						myApp.alert(_("加载失败！"));
					}
					myApp.hideIndicator();//隐藏加载中
				}
			});
		},
         dataURLtoBlob:function(dataurl) {
			var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
			while(n--){
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], {type:mime});
		},
		unImg:function(StyleNo) {
            var isImg=false;
			var self=this;
			var len=$('.up-img').length;
			var formData=new FormData();
             for (var i=0;i<len;i++){
                 var dataSrc=$('.up-img').eq(i).attr('data-src');
                 if(dataSrc.indexOf('http://')==-1){
                     isImg=true;
                     var blob= self.dataURLtoBlob(dataSrc);
                     formData.append("image", blob, "image" + i + ".png");
                 }

             }
             if(!isImg){
                 if($('.video_file').length>0){
                     self.HandVideoStr(StyleNo)
                 }else {
                     self.addProduct();
                 }
                 return false;
             }
            myApp.showIndicator();
            var url;
            if(EDITMODE == true){
                url="/team/UploadImages?type=inlay-settings&styleNo="+StyleNo
            }else{
                url="/team/UploadImage?type=inlay-settings"
            }
			$.ajax({
				url: url,
				data: formData,
				type: 'POST',
				cache: false,
				processData: false,
				contentType: false,
				dataType: 'JSON',
				success: function(result) {
					var _result=eval('('+result+')');
					if(_result.result==true){
                        for(var i = 0; i < _result.successes.length; i++) {
                            $('.new_up').eq(i).attr('data-src', _result.successes[i][1]);
                        }
					}
                    if($('.video_file').length>0){
                        self.HandVideoStr(StyleNo)
                    }else {
                        self.addProduct();
                    }
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					myApp.alert(XMLHttpRequest.responseText);
				}

			});
		},

        //上传视频 start
        HandVideoStr:function(StyleNo) {
            myApp.showIndicator();
            var self=this;
            var fd = new FormData();
            var _this=document.getElementById("video_input");

            if($('#video_input').attr('data-url')){
                self.addProduct($('#video_input').attr('data-url'))
            }else {
                fd.append("fileToUpload", _this.files[0]);
                xhrVideo.onreadystatechange = function() {
                    self.videoFun();
                };
                if(EDITMODE == true){
                    xhrVideo.open("post", 'UploadVideos?type=inlay-settings&styleNo='+StyleNo, true);
                }else{
                    xhrVideo.open("post", 'UploadVideo?type=inlay-settings', true);
                }
                xhrVideo.send(fd);
            }

        },
        videoFun:function() {
            var self=this;
            var mp4Data='';
            if(xhrVideo.readyState == 4 && xhrVideo.status == 200) {
                var obj = $.parseJSON(xhrVideo.responseText);
                var _result = eval('(' + obj + ')'); //eval()解析单个json对象
                if(_result.msgcode == false) {
                    myApp.alert(_result.msginfo);
                } else {
                    if(_result.result==false){
                        self.addProduct(mp4Data)
                    }else {

                        mp4Data=_result.successes[0][1];
                        self.addProduct(mp4Data)
                    }
                }
            }
        },
        //上传视频end

		//新增提交
		addProduct:function(mp4Data){
			//图片链接
			var images=[];
			var img_sectionLength=$(".img-section").find("section.up-section").length;
			if(img_sectionLength==0){
				myApp.alert(_("请上传图片"));
				$(".sure2").hide();
				$(".sure1").show();
                myApp.hideIndicator();//隐藏加载中
			}else{
				 myApp.showPreloader(_("上传中，请稍等!"));
				//获取图片地址submit_btn
				for(var i=0;i<img_sectionLength;i++){
					var img_li=$(".img-section").find("section.up-section").eq(i);
					var img_src=img_li.find(".up-img").attr("data-src");
					images.push(img_src);
				}
                var imgs=images.join('|');//拼成字符串
	    		$("#Images").val(imgs);//图片
	    		$("#Category").val($("#data_category span.active").attr("data-value"));
			    var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
		             result[item.name] = item.value;
		            return result;
		        }, {})//把提交的数据转为JSON格式
                finalRes.Tag=$("#form_Tag").val();
                finalRes.Country=$("#form_Country").val();
		        if(EDITMODE){
					finalRes.GoodsType=7;
		        	var manageURL="/Team/ModifyProductData";
		        }else{
					finalRes.GoodsType=7;
		        	var manageURL="/Team/AddProductData";
		        }
                finalRes.Videos=mp4Data||'';//视频
				 $.ajax({
				 	type:"POST",
				 	url:manageURL,
				 	data:JSON.stringify(finalRes),
                     contentType: "application/json; charset=utf-8",
                     beforeSend:function(){
                         $(".sure1").hide();
                         $(".sure2").show();
                     },
                     success: function (result) {
	                	var _result = eval('(' + result + ')');//eval()解析单个json对象
	                     myApp.hidePreloader();
	                	if(EDITMODE){
							var tipString=_("修改");
	                	}else{
	                		var tipString=_("新增");
	                	}
	                	if(_result.result==true){
	                	    if(EDITMODE){
                                if(APP){
                                    var appJson={};
                                    appJson.isReFreshList=true;
                                    appJson.isReFreshGoods=true;
                                    appJson.isReFreshCurrentPage=false;
                                    YiYi_APP.refresh(JSON.stringify(appJson));
                                }
                            }else{
                                if(APP){
                                    var appJson={};
                                    appJson.isReFreshList=true;
                                    YiYi_APP.refresh(JSON.stringify(appJson));
                                }
                            }
	                		myApp.alert(tipString+_("成功！"));
	                	}else{
	                		myApp.alert(tipString+_("失败！"));
	                	}
                         myApp.hideIndicator();//隐藏加载中
                        $(".sure1").show();
                        $(".sure2").hide();
	                }
				 });
			}
			
		},
		
		//公共参数
		loadCommon:function(){
            var json_type=inlaysetting;
            //品类
            var $Type_new;
            for(var i = 0; i < json_type[1].Type.length; i++) {
                $Type_new += '<option value="' + json_type[1].Type[i][0] + '">' + _(json_type[1].Type[i][1]) + '</option>';
            }
            $("#form_Type").html($Type_new);
            //风格
            var $Style;
            for(var i = 0; i < json_type[1].Style.length; i++) {
                $Style += '<option value="' + json_type[1].Style[i][0] + '">' + _(json_type[1].Style[i][1]) + '</option>';
            }
            $("#form_Style").html($Style);

            //主石工艺
            var $technics;
            for(var i = 0; i < json_type[1].Technics.length; i++) {
                $technics += '<option value="' + json_type[1].Technics[i][0] + '">' + _(json_type[1].Technics[i][1]) + '</option>';
            }
            $("#form_Technics").html($technics);
            //材质
            var $material;
            for(var i = 0; i < json_type[1].Material.length; i++) {
                $material += '<option value="' + json_type[1].Material[i][0] + '">' + _(json_type[1].Material[i][1]) + '</option>';
            }
            $("#form_material").html($material);

            //形状
            var $MainShape;
            for(var i = 0; i < json_type[1].MainShape.length; i++) {
                $MainShape += '<option value="' + json_type[1].MainShape[i][0] + '">' + _(json_type[1].MainShape[i][1]) + '</option>';
            }
            $("#form_MainShape").html($MainShape);

            //所在地
            var $Country;
            for(var i = 0; i < json_type[1].Country.length; i++) {
                $Country += '<option value="' + json_type[1].Country[i][0] + '">' + _(json_type[1].Country[i][1]) + '</option>';
            }
            $("#form_Country,#_batchplace").html($Country);

            //供货方式
            var $IsStock;
            for(var i = 0; i < json_type[1].IsStock.length; i++) {
                $IsStock += '<option value="' + json_type[1].IsStock[i][0] + '">' + _(json_type[1].IsStock[i][1]) + '</option>';
            }
            $("#form_IsStock").html($IsStock);
            //状态
            var $Status;
            for(var i = 0; i < json_type[1].Status.length; i++) {
                $Status += '<option value="' + json_type[1].Status[i][0] + '">' + _(json_type[1].Status[i][1]) + '</option>';
            }
            $("#form_Status").html($Status);

            //支付状态
            // var $ReceiptStatus;
            // for(var i = 0; i < json_type[1].ReceiptStatus.length; i++) {
            //     $ReceiptStatus += '<option value="' + json_type[1].ReceiptStatus[i][0] + '">' + _(json_type[1].ReceiptStatus[i][1]) + '</option>';
            // }
            // $("#form_ReceiptStatus").html($ReceiptStatus);
		},

	}
	addForm.init();
})();
// function dddd(e) {
//     alert(5454)
//     e.stopPropagation();
// }
//付款
function formatReceiptStatus(val){
    if(val==0){
        return _("未支付");
    }else if(val==1){
        return _("已支付");
    }
}

function calc6(){
    var g_price=$("#g_price").val();  //金价
    var netGoldWeight=$("#NetGoldWeight").val(); //净金重
    var wastage=$("#wastage").val(); //损耗
    var sidePrice="";
    if($("#SidePrice").val()!=""){
        sidePrice=$("#SidePrice").val();  //副石金额
    }else{
        sidePrice=0;
    }
    var unitPrice=$("#unitPrice").val(); //工费
    var insurance=$("#insurance").val(); //保险费
    var sideLaborFee=Number($("#sideLaborFee").val())*Number($("#sideNum").val()); //副石工费
    if(g_price){
        $("#tolPrice").val(formatRMBPrice((parseFloat(g_price)*parseFloat(netGoldWeight)*parseFloat(1+parseFloat(wastage))+parseFloat(sidePrice)+parseFloat(unitPrice)+parseFloat(insurance)+parseFloat(sideLaborFee))));
    }
}

//兼容转换blob
function getObjectURL (file) {
    var url = null
    if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
    } else if (window.URL !== undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
    } else if (window.webkitURL !== undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
    }
    return url
}

//兼容IOS时间显示
function GetDateDiff(DiffTime) {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
    Time = DiffTime.replace(/\-/g, "/");
    return Time;
}




